<template>
  <div>
    <page-tabs :total="total" :loading="loading" />
    <div class="pageTop">
      <page-search
        :search-params="searchParams"
        :store="store"
        :date-obj="dateObj"
        :search-carrier-obj="searchCarrierObj"
        :page-name="pageName"
        :father-init="init"
        :checked-country-res="checkedCountryRes"
        @emptyCarrier="emptyCarrier"
        @emptyFilter="emptyFilter"
      />

      <sticky :z-index="8" :sticky-top="50">
        <button-area
          :page-name="pageName"
          :search-params="searchParams"
          :father-init="init"
          :show-note-dialog="showNoteDialog"
          :bind-design="bindDesign"
          :order-confirm="orderConfirm"
          :order-go-back="orderGoBack"
          :order-submit="orderSubmit"
          :show-channel-dialog="showChannelDialog"
          :show-move-dialog="showMoveDialog"
          :order-urgent="orderUrgent"
          :order-export="orderExport"
          :show-appeal-dialog="showAppealDialog"
          :order-trash="orderTrash"
          :order-packing="orderPacking"
          :order-recover="orderRecover"
          :order-delete="orderDelete"
          :apply-label="applyLabel"
        />
      </sticky>
    </div>

    <!-- Pending -->
    <el-table
      ref="multipleTable"
      v-loading="loading"
      border
      :data="tableData"
      style="width: 100%;"
      @selection-change="handleSelectionChange"
      @row-click="rowClick"
    >
      <el-table-column type="selection" width="30" />
      <el-table-column prop="order.orderNumber" label="Order No" width="120" />
      <el-table-column prop="product" label="Product" width="360">
        <template slot-scope="scope">
          <product-info
            :scope-row="scope.row"
            :page-name="pageName"
            :to-proview="toProview"
            :show-design-dialog="showDesignDialog"
            :inline-search="inlineSearch"
          />
          <div
            v-if="orderErr.orderNos.indexOf(scope.row.order.orderNumber) > -1"
            class="orderErr"
          >
            <el-alert
              :title="orderErr.errTips[scope.row.order.orderNumber]"
              show-icon
              type="error"
              @close="closeArrAlert(scope.row.order.orderNumber, $event)"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="Buyer" width="170">
        <template slot-scope="slotScope">
          <buyer :row="slotScope.row" :inline-search="inlineSearch" />
        </template>
      </el-table-column>
      <el-table-column label="Date" width="246">
        <template slot-scope="slotScope">
          <time-axis
            :key="slotScope.row.order.orderNumber"
            :row="slotScope.row.order"
          />
        </template>
      </el-table-column>
      <el-table-column label="Shipping">
        <template slot-scope="slotScope">
          <shipping :row="slotScope.row" />
        </template>
      </el-table-column>
      <el-table-column label="Note">
        <template slot-scope="scope">
          <p v-if="scope.row.order.dealerNote" class="note">
            <span class="proDescription">business:</span>{{ scope.row.order.dealerNote }}
          </p>
          <p v-if="scope.row.order.customerNote" class="note">
            <span class="proDescription">customer:</span>{{ scope.row.order.customerNote }}
          </p>
        </template>
      </el-table-column>
      <el-table-column label="Status">
        <template slot-scope="scope">
          <status :row="scope.row" :page-name="pageName" />
        </template>
      </el-table-column>
      <el-table-column label="Operation" width="110">
        <template slot-scope="slotScope">
          <operations
            :scope="slotScope"
            :order-det="orderDet"
            :page-name="pageName"
            :show-resend-dialog="showResendDialog"
            :order-confirm="orderConfirm"
            :order-submit="orderSubmit"
            :order-go-back="orderGoBack"
            :show-note-dialog="showNoteDialog"
            :show-channel-dialog="showChannelDialog"
            :order-urgent="orderUrgent"
            :order-unurgent="orderUnurgent"
            :order-packing="orderPacking"
            :order-delete="orderDelete"
            :to-split="toSplit"
          />
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-if="tableData.length"
      id="btmPagination"
      :class="{ open: sidebar }"
      :current-page="pageNo"
      :page-sizes="[10, 30, 50, 100, 200]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      class="pagination_wrap"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- order详情 -->
    <order-detail
      v-if="orderDetVisible"
      :id="detailId"
      :father-init="init"
      @closeDet="closeDet()"
    />

    <!-- 选择物流弹窗 -->
    <el-dialog
      title="Choice Carrier"
      :visible.sync="carrierVisible"
      width="400px"
    >
      <template v-if="selfCarrier">
        <el-select
          v-model="otherLogisticsId"
          style="width: 270px;"
          @visible-change="getLogisticsList"
        >
          <el-option
            v-for="item in logisticsList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </template>
      <template v-else>
        <el-select v-model="freightId" style="width: 270px;">
          <el-option
            v-for="item in channelData"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </template>

      <div slot="footer" class="dialog-footer">
        <el-button @click="carrierVisible = false">Cancel</el-button>
        <el-button
          v-if="carrierType === 'submit'"
          v-preventReClick
          :disabled="freightId === ''"
          type="primary"
          @click="orderSubmit()"
        >Submit</el-button>
        <template v-if="carrierType === 'change'">
          <el-button
            v-if="selfCarrier"
            v-preventReClick
            :disabled="otherLogisticsId === ''"
            type="primary"
            @click="changeChannel(selfCarrier)"
          >Confirm</el-button>
          <el-button
            v-else
            v-preventReClick
            :disabled="freightId === ''"
            type="primary"
            @click="changeChannel(selfCarrier)"
          >Confirm</el-button>
        </template>
      </div>
    </el-dialog>

    <!-- 重发弹窗 -->
    <el-dialog title="Resend" :visible.sync="resendVisible">
      <div>
        <p>Carrier: <span>Epacket</span></p>
        <p>Order ID: <span>1952</span></p>
      </div>
      <el-form :model="resendData" label-width="100px">
        <el-form-item label="Reason">
          <el-select v-model="resendData.region" placeholder="请选择活动区域">
            <el-option
              v-for="(item, index) of reasonOptions"
              :key="index"
              label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="Note">
          <el-input v-model="resendData.note" autocomplete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resendVisible = false">Cancel</el-button>
        <el-button
          v-preventReClick
          type="primary"
          @click="resendVisible = false"
        >Confirm</el-button>
      </div>
    </el-dialog>

    <!-- 匹配设计弹窗 -->
    <el-dialog
      v-show="!addDesignVisible"
      class="bingDesignDialog"
      title="Bind designs"
      :visible.sync="designVisible"
      width="750px"
      @close="closeDesignDialog"
    >
      <div class="topSearch">
        <el-input v-model="designSearchObj.sku" clearable placeholder="Name" />
        <el-input v-model="designSearchObj.name" clearable placeholder="Sku" />
        <el-select
          v-model="designSearchObj.materialGroupId"
          placeholder="Select group"
          class="topSelect"
          @visible-change="getDesignGrop"
        >
          <el-option label="All" :value="0" />
          <el-option
            v-for="item in groupOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
        <el-button
          v-preventReClick
          type="primary"
          @click="searchDesign"
        >Search</el-button>
        <el-button type="primary" @click="showAddDesign">Add designs</el-button>
      </div>
      <el-table
        ref="designTable"
        class="designTable"
        :data="materialArr"
        :row-class-name="designRowClassName"
        height="300px"
        style="margin-bottom:10px;"
        @row-click="designRowClick"
      >
        <el-table-column width="30">
          <template slot-scope="scope">
            <el-radio
              v-model="isBeginSelect"
              class="designRadio"
              :label="scope.$index"
              @change.native="changeDesignCurrent(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column type="expand" width="40">
          <template slot-scope="scope">
            <el-row v-if="scope.row.variants.length" :gutter="20">
              <el-col
                v-for="item in scope.row.variants"
                :key="item.id"
                class="productItem"
                :span="12"
              >
                <el-image
                  class="productImg"
                  :src="imgPrefix + item.thumbnailUri"
                  @click="toProview(imgPrefix + item.thumbnailUri)"
                />
                <p><span>Sku: </span>{{ item.variantSku }}</p>
              </el-col>
            </el-row>
            <p v-else style="text-align:center;color:#848484">No Products</p>
          </template>
        </el-table-column>
        <el-table-column label="Image" width="90">
          <template slot-scope="scope">
            <el-image
              class="productImg"
              :src="
                scope.row.material.thumbnailUri.indexOf('http') === 0
                  ? scope.row.material.thumbnailUri
                  : imgPrefix + scope.row.material.thumbnailUri + imgSuffix
              "
              @click="
                toProview(
                  scope.row.material.thumbnailUri.indexOf('http') === 0
                    ? scope.row.material.thumbnailUri
                    : imgPrefix + scope.row.material.thumbnailUri
                )
              "
            />
          </template>
        </el-table-column>
        <el-table-column prop="material.sku" label="Name" />
        <el-table-column label="Sku">
          <template slot-scope="scope">
            <el-tag
              v-for="item in scope.row.variants"
              :key="item.id"
              style="margin-right:5px;"
            >{{ item.variantSku }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="Group" width="130">
          <template slot-scope="scope">
            {{
              scope.row.material.materialGroupId === 0
                ? 'no'
                : groupMap[scope.row.material.materialGroupId]
            }}
          </template>
        </el-table-column>
        <div
          v-if="designloading !== 0 && designPageNo !== 1"
          slot="append"
          style="text-align:center;line-height:30px;color:#848484"
        >
          {{ designloading === 1 ? 'loading' : 'end' }}
        </div>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <div class="bindDesignFooter">
          <el-checkbox
            v-model="isReplace"
            :true-label="1"
            :false-label="0"
          >Please make sure that the design you choose is correct, and we will
            bind this design to other oreders of the same product.</el-checkbox>
        </div>
        <el-button @click="closeDesignDialog">Cancel</el-button>
        <el-button
          v-preventReClick
          type="primary"
          :disabled="Object.keys(selectDesign).length === 0"
          @click="bindDesign"
        >Confirm</el-button>
      </div>
    </el-dialog>

    <!-- 添加设计 -->
    <add-design
      v-if="addDesignVisible"
      @closeAddDesign="closeAddDesign"
      @addDesignSucc="addDesignSucc"
    />

    <!-- move -->
    <el-dialog title="Fulfill Self" :visible.sync="moveVisible" width="450px">
      <el-select
        v-model="logisticId"
        style="width: 270px;"
        @visible-change="getLogisticsList"
      >
        <el-option
          v-for="item in logisticsList"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
      <div slot="footer" class="dialog-footer">
        <el-button @click="moveVisible = false">Cancel</el-button>
        <el-button
          v-preventReClick
          :disabled="logisticId === ''"
          type="primary"
          @click="orderPacking()"
        >Move</el-button>
      </div>
    </el-dialog>

    <!-- 拆分订单 -->
    <splitOrder
      v-if="splitOrderData.canSplit"
      :split-order-data="splitOrderData"
      :split-order="splitOrder"
    />

    <!-- 订单备注 -->
    <el-dialog title="Note" :visible.sync="noteVisible" width="450px">
      <el-input
        v-model="note"
        type="textarea"
        placeholder="Please fill in the notes"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="noteVisible = false">Cancel</el-button>
        <el-button
          v-preventReClick
          type="primary"
          @click="addNote"
        >Confirm</el-button>
      </div>
    </el-dialog>

    <!-- 订单申诉 -->
    <el-dialog title="Appeal" :visible.sync="appealVisible" width="450px">
      <el-input
        v-model="appealReason"
        type="textarea"
        placeholder="Please fill in the notes"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="appealVisible = false">Cancel</el-button>
        <el-button
          v-preventReClick
          type="primary"
          @click="appealAdd"
        >Confirm</el-button>
      </div>
    </el-dialog>

    <!-- 图片预览 -->
    <proview-img v-if="proviewUrl" :src="proviewUrl" @close="closeProview" />
  </div>
</template>

<script>
import {
  orderExport,
  orderConfirm,
  orderPage,
  bindDesign,
  batchBindDesign,
  orderGoBack,
  orderTrash,
  orderNote,
  orderUrgent,
  orderUnurgent,
  selfFulfill,
  orderRecover,
  changeChannel,
  changeOtherChannel,
  orderDelete,
  applyLabel
} from '@/api/store';
import { logisticsList } from '@/api/logistics';
import { orderSubmit } from '@/api/authorized';
import { freightList, countries } from '@/api/common';
import { materialPage, materialGroupList } from '@/api/material';
import { appealAdd } from '@/api/appeal';
import Sticky from '@/components/Sticky';
import ProviewImg from '@/components/Proview/proviewImg';
import PageTabs from './pageTab';
import PageSearch from './pageSearch';
import ButtonArea from './buttonArea';
import ProductInfo from './productInfo';
import Buyer from './buyer';
import TimeAxis from './timeAxis';
import Shipping from './shipping';
import Status from './status';
import Operations from './operations';
import SplitOrder from './splitOrder';
import OrderDetail from './orderDetail';
import AddDesign from './addDesign';
import { jointOrderIds } from '@/utils/orderUtils';
import { postResult } from '@/utils/dataFormat';
import bus from '@/utils/bus';
export default {
  provide() {
    return {
      // 国家相关
      countryData: () => this.countryData,
      cloneCountryMap: this.cloneCountryMap,
      countryMap: () => this.countryMap,
      countryOptions: () => this.countryOptions,
      checkedCountryRes: () => this.checkedCountryRes
    };
  },
  components: {
    PageTabs,
    PageSearch,
    ButtonArea,
    Sticky,
    ProductInfo,
    Buyer,
    TimeAxis,
    Shipping,
    Status,
    Operations,
    SplitOrder,
    OrderDetail,
    ProviewImg,
    AddDesign
  },
  props: {
    pageName: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      proviewUrl: '',
      routerName: this.$route.name,
      loading: false,
      tableData: [],
      multipleSelection: [],
      pageNo: 1,
      pageSize: 10,
      total: 0,
      storeType: '',
      storeOptions: [
        {
          value: 'shopify',
          label: 'shopify'
        },
        {
          value: 'woocommerce',
          label: 'woocommerce'
        }
      ],
      searchParams: {},
      store: {
        id: -1
      },
      dateObj: {},
      searchCarrierObj: {},
      cloneCountryMap: {
        countryMap: {}
      },
      countryMap: {},
      countryData: [],
      checkedCountryRes: [],
      selfCarrier: true,
      carrierType: 'change',
      orderDetVisible: false,
      detailId: '',
      carrierVisible: false,
      channelOrderId: '',
      channelData: [],
      logisticsList: [],
      logisticId: '',
      moveVisible: false,
      freightId: '',
      otherLogisticsId: '',
      resendVisible: false,
      resendData: {},
      reasonOptions: [
        {
          value: 'Goods not received',
          label: 'Goods not received'
        },
        {
          value: 'Quality',
          label: 'Quality'
        },
        {
          value: 'Quantity',
          label: 'Quantity'
        },
        {
          value: 'Size',
          label: 'Size'
        },
        {
          value: 'Address error',
          label: 'Address error'
        },
        {
          value: 'Others',
          label: 'Others'
        }
      ],
      designVisible: false,
      addDesignVisible: false,
      splitOrderData: {
        canSplit: false,
        data: {}
      },
      materialArr: [],
      selectDesign: {},
      isBeginSelect: false,
      designSearchObj: {},
      designloading: 0, // 0初始化，1加载中，2到底
      designPageSize: 5,
      designPageNo: 1,
      totalPages: 0,
      orderDetailId: 0,
      orderId: 0,
      isReplace: 0,
      groupOptions: [],
      groupMap: {},
      noteVisible: false,
      addNoteType: '',
      editNoteId: '',
      note: '',
      appealVisible: false,
      appealIds: [],
      appealReason: '',
      orderErr: {
        // 接口返回错误信息
        orderNos: [],
        errTips: {}
      }
    };
  },
  computed: {
    sidebar() {
      return this.$store.state.app.sidebar.opened;
    }
  },
  watch: {
    pageName(newV, oldV) {
      this.init();
    }
  },
  beforeDestroy() {
    bus.$off('checkedCountry');
  },
  mounted() {
    bus.$on('checkedCountry', (data) => {
      this.checkedCountryRes = data;
      this.init();
    });
    if (this.$route.params.storeId) {
      this.store.id = this.$route.params.storeId;
    }
    this.init();
    this.getFreightList();
    this.getCountriesList();
    if (this.pageName === 'PENDING') {
      this.getDesignGrop(true);
    }
  },
  methods: {
    init() {
      this.loading = true;
      orderPage({
        ...this.searchParams,
        ...this.searchCarrierObj,
        beginDate: this.dateObj.beginDate,
        endDate: this.dateObj.endDate,
        dateField: this.dateObj.dateField,
        storeId: this.store.id,
        countryCodes: this.checkedCountryRes,
        orderStatus: this.pageName,
        pageNo: this.pageNo,
        pageSize: this.pageSize
      }).then((res) => {
        this.loading = false;
        this.tableData = res.data.data || [];
        this.total = res.data.totalCount;
      });
    },
    emptyCarrier() {
      this.searchCarrierObj = {};
    },
    emptyFilter() {
      // 清除筛选项
      this.checkedCountryRes = [];
      this.searchCarrierObj = {};
      this.searchParams = {};
      this.dateObj = {};
      this.store = {
        id: -1
      };
      this.init();
    },
    inlineSearch(label, val) {
      switch (label) {
        case 'store':
          this.store.id = val;
          break;
        case 'country':
          this.checkedCountryRes.push(val);
          break;
        case 'name':
          this.$set(this.searchParams, 'consigneeName', val);
          break;
        case 'sku':
          this.$set(this.searchParams, 'sku', val);
          break;
        case 'carrier':
          this.$set(this.checkedLogisticRes, 0, val);
          break;
      }
      this.init();
    },
    getFreightList() {
      freightList().then((res) => {
        this.channelData = res.data;
      });
    },
    getLogisticsList(val) {
      if (val) {
        logisticsList().then((res) => {
          this.logisticsList = res.data;
        });
      }
    },
    getCountriesList() {
      countries().then((res) => {
        this.countryOptions = res.data;
        const arr = res.data;
        const countryData = [...new Set(arr.map((e) => e.area))].map((a) => ({
          fieldType: String(a),
          favorites: arr.filter((x) => x.area === a)
        }));
        const obj = {};
        arr.forEach((item) => {
          obj[item.code] = item.englishName;
        });
        this.countryMap = obj;
        this.cloneCountryMap['countryMap'] = obj;
        this.countryData = countryData;
      });
    },
    applyLabel(type, id) {
      const ids = jointOrderIds(
        type,
        id,
        this.multipleSelection,
        this.$message
      );
      applyLabel({
        isUnshipped: 0,
        orderIds: ids
      }).then((res) => {
        if (res.code === 200) {
          if (res.data.length) {
            res.data.forEach((item) => {
              window.open(item);
            });
          } else {
            this.$message.warning('No information was obtained');
          }
        }
      });
    },
    orderExport(val) {
      // 订单导出
      const params = {
        ...this.searchParams,
        ...this.searchCarrierObj,
        beginDate: this.dateObj.beginDate,
        endDate: this.dateObj.endDate,
        dateField: this.dateObj.dateField,
        storeId: this.store.id,
        countryCodes: this.checkedCountryRes,
        orderStatus: this.pageName,
        pageNo: this.pageNo,
        pageSize: this.pageSize
      };
      if (val === '1') {
        const ids = jointOrderIds(
          'more',
          null,
          this.multipleSelection,
          this.$message
        );
        if (!ids) return;
        params['orderIds'] = ids;
      }
      orderExport(params).then((res) => {
        if (res && res.status === 200) {
          this.downloadByBlob(res, this.$message);
        }
      });
    },
    orderConfirm(type, id) {
      // 提交生产
      const ids = jointOrderIds(
        type,
        id,
        this.multipleSelection,
        this.$message
      );
      if (!ids) return;
      orderConfirm(ids).then((res) => {
        postResult(res, this.$message, this.init);
      });
    },
    orderGoBack(type, id) {
      // 回退
      const ids = jointOrderIds(
        type,
        id,
        this.multipleSelection,
        this.$message
      );
      if (!ids) return;
      orderGoBack({ orderIds: ids, orderStatus: this.pageName }).then((res) => {
        postResult(res, this.$message, this.init);
      });
    },
    orderSubmit() {
      // 提交生产
      orderSubmit({
        orderIds: this.channelOrderId,
        freightId: this.freightId
      }).then((res) => {
        if (res.code === 200) {
          this.freightId = '';
          this.carrierVisible = false;
          if (res.data.length > 0) {
            const orderNos = [];
            const tips = {};
            res.data.forEach((item) => {
              if (orderNos.indexOf(item.orderNo) === -1) {
                orderNos.push(item.orderNo);
                tips[item.orderNo] = item.note;
              }
            });
            this.$set(this.orderErr, 'orderNos', orderNos);
            this.$set(this.orderErr, 'errTips', tips);
            this.$message.warning({
              dangerouslyUseHTMLString: true,
              message: `
              <p>OrderNo：${orderNos.join(', ')}。Error occurred</p>
            `,
              duration: 6000,
              showClose: true
            });
            if (res.data.length < this.channelOrderId.length) {
              this.init();
            }
          } else {
            this.$message.success('success');
            this.init();
          }
        }
      });
    },
    closeArrAlert(orderNo, e) {
      // 关闭错误提示
      const arrNo = JSON.parse(JSON.stringify(this.orderErr.orderNos));
      const arrTip = JSON.parse(JSON.stringify(this.orderErr.errTips));
      arrNo.splice(arrNo.indexOf(orderNo), 1);
      delete arrTip[orderNo];
      this.$set(this.orderErr, 'orderNos', arrNo);
      this.$set(this.orderErr, 'errTips', arrTip);
    },
    orderUrgent(type, id) {
      // 加急
      const ids = jointOrderIds(
        type,
        id,
        this.multipleSelection,
        this.$message
      );
      if (!ids) return;
      orderUrgent(ids).then((res) => {
        postResult(res, this.$message, this.init);
      });
    },
    orderUnurgent(id) {
      orderUnurgent([id]).then((res) => {
        postResult(res, this.$message, this.init);
      });
    },
    showNoteDialog(addType, order) {
      // 显示输入备注弹窗
      if (addType === 'more' && this.multipleSelection.length < 1) {
        return this.$message.warning(
          'Please select at least one piece of data'
        );
      }
      this.addNoteType = addType;
      this.editNoteId = addType === 'one' ? order.id : '';
      this.note = addType === 'one' ? order.dealerNote : '';
      this.noteVisible = true;
    },
    addNote() {
      // 添加备注
      const ids = jointOrderIds(
        this.addNoteType,
        this.editNoteId,
        this.multipleSelection,
        this.$message
      );
      if (!this.note.trim()) {
        return this.$message.warning(
          'Please enter valid information in the field !'
        );
      }
      orderNote({ note: this.note.trim(), orderIds: ids }).then((res) => {
        postResult(res, this.$message, this.init);
        this.noteVisible = false;
      });
    },
    orderTrash(type, id) {
      // 删除订单
      this.$confirm(
        'This action will delete the order. Do you want to continue?',
        'Hint',
        {
          confirmButtonText: 'Yes',
          cancelButtonText: 'No',
          type: 'warning'
        }
      )
        .then(() => {
          const ids = jointOrderIds(
            type,
            id,
            this.multipleSelection,
            this.$message
          );
          if (!ids) return;
          orderTrash(ids).then((res) => {
            postResult(res, this.$message, this.init);
          });
        })
        .catch(() => {});
    },
    showAppealDialog(type, id) {
      if (type === 'more' && this.multipleSelection.length < 1) {
        return this.$message.warning(
          'Please select at least one piece of data'
        );
      }
      this.appealIds = jointOrderIds(
        type,
        id,
        this.multipleSelection,
        this.$message
      );
      this.appealReason = '';
      this.appealVisible = true;
    },
    appealAdd() {
      appealAdd({
        orderIds: this.appealIds,
        reason: this.appealReason,
        type: 'ORDER'
      }).then((res) => {
        this.appealVisible = false;
        postResult(res, this.$message, this.init);
      });
    },
    orderPacking() {
      // 移至Packing
      selfFulfill({
        orderIds: this.channelOrderId,
        otherLogisticsId: this.logisticId
      }).then((res) => {
        this.logisticId = '';
        this.moveVisible = false;
        postResult(res, this.$message, this.init);
      });
    },
    orderRecover(type, id) {
      // 回退
      const ids = jointOrderIds(
        type,
        id,
        this.multipleSelection,
        this.$message
      );
      if (!ids) return;
      orderRecover(ids).then((res) => {
        postResult(res, this.$message, this.init);
      });
    },
    showChannelDialog(type, id, state, self) {
      // type：是否批量，id：单个修改时传入ID，state：'change'修改/'submit'提交生产，self:自建物流信息
      // 显示选择物流弹窗
      this.selfCarrier = self || false;
      this.carrierType = state;
      const ids = jointOrderIds(
        type,
        id,
        this.multipleSelection,
        this.$message
      );
      if (!ids) return;
      this.channelOrderId = ids;
      this.carrierVisible = true;
    },
    showMoveDialog(type, id) {
      const ids = jointOrderIds(
        type,
        id,
        this.multipleSelection,
        this.$message
      );
      if (!ids) return;
      this.channelOrderId = ids;
      this.moveVisible = true;
    },
    changeChannel(state) {
      // true:自定义, false:freight
      const httpUrl = state ? changeOtherChannel : changeChannel;
      const params = state
        ? {
          orderIds: this.channelOrderId,
          otherLogisticsId: this.otherLogisticsId
        }
        : {
          orderIds: this.channelOrderId,
          freightId: this.freightId
        };
      httpUrl(params).then((res) => {
        if (res.code === 200) {
          if (state) {
            this.otherLogisticsId = '';
          } else {
            this.freightId = '';
          }
          this.carrierVisible = false;
          if (res.data.length > 0) {
            const orderNos = [];
            const tips = {};
            res.data.forEach((item) => {
              if (orderNos.indexOf(item.orderNo) === -1) {
                orderNos.push(item.orderNo);
                tips[item.orderNo] = item.note;
              }
            });
            this.$set(this.orderErr, 'orderNos', orderNos);
            this.$set(this.orderErr, 'errTips', tips);
            this.$message.warning({
              dangerouslyUseHTMLString: true,
              message: `
              <p>OrderNo：${orderNos.join(', ')}。Error occurred</p>
            `,
              duration: 6000,
              showClose: true
            });
            if (res.data.length < this.channelOrderId.length) {
              this.init();
            }
          } else {
            this.$message.success('success');
            this.init();
          }
        }
      });
    },
    showResendDialog() {
      this.resendVisible = true;
    },
    showDesignDialog(orderId, detailId, boolean) {
      // boolean：true-重复匹配；不传-首次匹配
      // 显示绑定设计弹窗
      this.designPageNo = 1;
      this.totalPages = 0;
      this.designloading = 0;
      this.materialArr = [];
      this.orderDetailId = detailId;
      this.orderId = orderId;
      this.isReplace = boolean ? 1 : 0;
      this.isBeginSelect = false;
      this.designVisible = true;
      this.getDesign();
      this.$nextTick(() => {
        this.scrollLoad();
      });
    },
    handleCellClick(row, cell) {
      if (cell.label === 'Sku') {
        this.$refs.dragTable.toggleRowExpansion(row);
      }
    },
    closeDesignDialog() {
      this.designVisible = false;
      this.$refs.designTable.clearSelection();
      this.selectDesign = {};
    },
    searchDesign() {
      // 搜索设计
      const dom = document.querySelector(
        '.designTable .el-table__body-wrapper'
      );
      dom.removeEventListener('scroll', this.scrollListen);
      this.$refs.designTable.clearSelection();
      this.selectDesign = {};
      this.designPageNo = 1;
      this.getDesign(true);
    },
    getDesign(boolean) {
      // 设计列表
      // boolean有值则是搜索
      this.designloading = 1;
      materialPage({
        pageSize: this.designPageSize,
        pageNo: this.designPageNo,
        ...this.designSearchObj
      }).then((res) => {
        this.designloading = 0;
        this.totalPages = res.data.totalPages;
        if (boolean) {
          this.materialArr = res.data.data;
          const dom = document.querySelector(
            '.designTable .el-table__body-wrapper'
          );
          setTimeout(() => {
            dom.addEventListener('scroll', this.scrollListen);
          }, 0);
          return;
        } else {
          this.materialArr = this.materialArr.concat(res.data.data);
        }
      });
    },
    showAddDesign() {
      this.addDesignVisible = true;
    },
    closeAddDesign(state) {
      this.addDesignVisible = false;
      if (state) {
        this.getDesign();
      }
    },
    addDesignSucc() {},
    scrollLoad() {
      const dom = document.querySelector(
        '.designTable .el-table__body-wrapper'
      );
      dom.addEventListener('scroll', this.scrollListen);
    },
    scrollListen() {
      const dom = document.querySelector(
        '.designTable .el-table__body-wrapper'
      );
      const scrollD = dom.scrollHeight - dom.scrollTop - dom.clientHeight;
      if (scrollD <= 0) {
        if (this.designPageNo < this.totalPages) {
          this.designPageNo++;
          this.getDesign();
        } else {
          this.designloading = 2;
        }
      }
    },
    getDesignGrop(val) {
      if (!val) return;
      materialGroupList().then((res) => {
        const obj = {};
        res.data.forEach((item) => {
          obj[item.id] = item.name;
        });
        this.groupMap = obj;
        this.groupOptions = res.data;
      });
    },
    designRowClassName({ row, rowIndex }) {
      row.index = rowIndex;
    },
    designRowClick(row) {
      this.selectDesign = row;
      this.isBeginSelect = row.index;
    },
    changeDesignCurrent(val) {
      this.selectDesign = val;
    },
    bindDesign() {
      bindDesign({
        orderDetailId: this.orderDetailId,
        materialId: this.selectDesign.material.id,
        isReplace: this.isReplace,
        orderId: this.orderId
      }).then((res) => {
        this.designVisible = false;
        postResult(res, this.$message, this.init);
      });
    },
    batchBindDesign() {
      batchBindDesign({
        materialId: this.selectDesign.material.id
      }).then((res) => {
        this.designVisible = false;
        postResult(res, this.$message, this.init);
      });
    },
    orderDelete(type, id) {
      const ids = jointOrderIds(
        type,
        id,
        this.multipleSelection,
        this.$message
      );
      if (!ids) return;
      this.$confirm(
        'This action will permanently delete the orders. Do you want to continue?',
        'Hint',
        {
          confirmButtonText: 'Confirm',
          cancelButtonText: 'cancel',
          type: 'warning'
        }
      )
        .then(() => {
          orderDelete(ids).then((res) => {
            postResult(res, this.$message, this.init);
          });
        })
        .catch(() => {});
    },
    toSplit(data) {
      if (!data) {
        if (this.multipleSelection.length !== 1) {
          this.$message.warning('Please select one piece of orders');
          return;
        }
        this.splitOrderData.data = this.multipleSelection[0];
      } else {
        this.splitOrderData.data = data;
      }
      this.splitOrderData.canSplit = true;
    },
    splitOrder(id, params) {
      // 拆分
      // if (!this.splitOrderData.isInit) {
      //   const order = {
      //     orderId: row.orderDTO.id,
      //     orderNumber: row.orderDTO.orderNumber,
      //     products: products
      //   }
      //   this.splitOrderData.order = Object.assign({}, order)
      //   this.splitOrderData.isInit = true
      // }
    },
    rowClick(row, column) {
      if (!column || column.label === 'Product') {
        return;
      }
      this.$refs.multipleTable.toggleRowSelection(row);
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    downloadByBlob(res, message) {
      // 下载blob数据
      if (JSON.stringify(res) !== '{}') {
        message.success('The file has been downloaded');
        const contentDisposition = res.headers['content-disposition'];
        if (
          contentDisposition.indexOf('fileName') >= 0 ||
          contentDisposition.indexOf('filename') >= 0
        ) {
          const filename =
            contentDisposition.split('fileName=')[1] ||
            contentDisposition.split('filename=')[1];
          const blob = new Blob([res.data]);
          const downloadElement = document.createElement('a');
          const href = window.URL.createObjectURL(blob); // 创建下载的链接
          downloadElement.href = href;
          downloadElement.download = filename; // 下载后文件名
          document.body.appendChild(downloadElement);
          downloadElement.click(); // 点击下载
          document.body.removeChild(downloadElement); // 下载完成移除元素
          window.URL.revokeObjectURL(href); // 释放掉blob对象
        }
      } else {
        message.error(
          'An error occurred while downloading. No infomation available!'
        );
      }
    },
    toProview(url) {
      // 预览图片
      this.proviewUrl = url;
    },
    closeProview() {
      // 关闭预览
      this.proviewUrl = '';
      document.querySelector('body').removeAttribute('style');
    },
    orderDet(id) {
      this.detailId = id;
      this.orderDetVisible = true;
    },
    closeDet() {
      this.orderDetVisible = false;
      this.detailId = null;
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.init();
    },
    handleCurrentChange(val) {
      this.pageNo = val;
      this.init();
    }
  }
};
</script>
<style lang="scss" scoped>
.orderErr {
  .el-alert {
    position: absolute;
    width: 600px;
    z-index: 20;
    top: 10px;
    padding: 4px 30px 4px 8px;
    ::v-deep.el-alert__closebtn {
      top: 10px;
    }
  }
}
.statusTag {
  .el-tag {
    margin-bottom: 4px;
    height: auto;
    white-space: inherit;
    line-height: 18px;
  }
}
.designTable {
  >>> .el-table__header-wrapper .el-checkbox {
    display: none;
  }
  >>> .el-checkbox__inner {
    border-radius: 50%;
  }
  .designRadio {
    ::v-deep .el-radio__label {
      display: none;
    }
  }
  ::v-deep.el-table__expanded-cell {
    padding: 10px 50px;
  }
  .productItem {
    display: flex;
    align-items: center;
    background-color: #f5f5f5;
    border-right: 2px solid #fff;
    border-bottom: 2px solid #fff;
    .el-image {
      margin-right: 10px;
    }
    span {
      font-weight: 600;
    }
  }
}
::v-deep.el-table--border th:first-child .cell,
::v-deep.el-table--border td:first-child .cell {
  padding-left: 8px;
}
.note {
  padding: 3px 5px;
  background: #f1f1f1;
  border-radius: 4px;
  margin-bottom: 10px;
  line-height: 18px;
}
.bingDesignDialog {
  ::v-deep.el-dialog__body {
    padding-bottom: 5px;
  }
  .bindDesignFooter {
    position: relative;
    top: -10px;
    float: left;
    width: 450px;
    > .el-checkbox {
      width: 100%;
      display: flex;
      ::v-deep .el-checkbox__label {
        white-space: initial;
        text-align: left;
      }
    }
  }
}
</style>
